const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    poster: [],
    banner: [],
    purchaseList: [],
    purchaseBg: '',
    searchValue: '',
    hasLogin: false,
    hasShop: false,
    swiperHeight: '',
    stopTime: 10 * 60,
    videoContext:null,
    video_data: '',
    fullScreen: false,

    supplyList: [],
    shopInfo: null,
    type: 0,
    searchValue: '',
    page: 1,
    limit: 10,
    totalPages: 1,
    
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.data.hasLogin && this.getSupplyList();
    !this.data.hasLogin && this.getPosterData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  swiperHeight: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height; //图片高度
    var imgw = e.detail.width;
    var swiperH = winWid * imgh / imgw + "px" //等比设置swiper的高度。  即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度    ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
      swiperHeight: swiperH //设置高度
    })
  },
  addSupply() {
    wx.navigateTo({
      url: '/pages/supplyAdd/supplyAdd'
    })
  },
  getPosterData: function () {
    wx.showLoading({
      title: '加载中...',
    });
    let that = this;
    util.request(api.PosterUrl).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          poster: res.data.poster
        });
      }
      wx.hideLoading();
    }).finally(() => {
      wx.hideLoading();
    });
  },
  /**
   * 用户认证信息检查{未认证用户：跳转到商户认证界面，已认证用户跳转到首页}
   */
  checkShopInfo: function () {
    let shopInfo = wx.getStorageSync('shopInfo');
    if (shopInfo) {
      wx.showTabBar();
      this.setData({
        hasShop: true
      })
      this.getSupplyList();
      this.getIndexData();
    } else {
      this.setData({
        hasShop: false
      })
      wx.reLaunch({
        url: "/pages/auth/authenticationIdentityWait/authenticationIdentityWait"
      });
    }
  },
  getSupplyList(reachBottom = false) {
    wx.showLoading({
      title: '加载中...',
    });
    let that = this;
    util.request(api.SupplyList, {
      type: that.data.type,
      page: that.data.page,
      limit: that.data.limit,
      searchValue: that.data.searchValue
    }).then(function (res) {
      if (res.errno === 0) {
        let supplyList = res.data.list.map(item => {
          item.dueTime = util.formatTime2(new Date(item.dueTime), "Y/M/D");
          item.herbListImage && (item.herbListImage01 = item.herbListImage.split(',')[0])
          item.companyLogo = item.companyLogo || item.avatar;
          item.companyName = item.companyName || item.nickname;
          return item;
        });
        //触底加载新数据并保留老数据
        if (reachBottom) {
          supplyList = [...that.data.supplyList, ...supplyList]
        }
        that.setData({
          supplyList: supplyList,
          totalPages: res.data.pages
        });
        wx.hideLoading();
      }
    }).finally(() => {
      wx.hideLoading();
    });
  },
  openSupply(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let valueId = this.data.supplyList[index].id;

    var prefix = "/pages/supplyDetail/supplyDetail?id="
    wx.navigateTo({
      url: prefix + valueId,
    });
  },
  //按下事件开始  
  touchStart: function (e) {
    let that = this;
    that.setData({
      touchStart: e.timeStamp
    })
  },
  //按下事件结束  
  touchEnd: function (e) {
    let that = this;
    that.setData({
      touchEnd: e.timeStamp
    })
  },


  getIndexData: function () {
    wx.showLoading({
      title: '加载中...',
    });
    let that = this;
    util.request(api.IndexUrl, {
      searchValue: that.data.searchValue
    }).then(function (res) {
      if (res.errno === 0) {
        let purchaseList = res.data.purchaseList || [];
        // console.log(purchaseList);
        purchaseList = purchaseList.map(item => {
          item.publishDt = util.formatTime2(new Date(item.publishDt), "Y/M/D");
          item.dueTime = parseInt((new Date(item.dueTime).getTime() - new Date().getTime()));
          item.minTime = 10 * 60;
          return item;
        });
        that.setData({
          banner: res.data.banner,
          purchaseList: purchaseList,
          purchaseBg: res.data.purchaseBg
        });
      }
      wx.hideLoading();
    }).finally(() => {
      wx.hideLoading();
    });
  },
  viewMore() {
    // wx.setStorageSync('purchase_type', 1)
    // wx.switchTab({
    //   url: "../purchase/purchase?type=1"
    // });
    wx.switchTab({
      url: "/pages/supply/supply"
    });

    //this.navigateToPurchase(1, '待报价')
  },
  viewExtraMore(){
    this.navigateToPurchaseExtra(1, '经营范围外待报价')
  },
  navigateToPurchase(type, name) {
    wx.setStorageSync('purchase_type', type)
    wx.setStorageSync('purchase_name', name);
    wx.navigateTo({
      url: "/pages/purchase/purchase"
    });
  },
  navigateToPurchaseExtra(type, name) {
    wx.setStorageSync('purchase_extra_type', type)
    wx.setStorageSync('purchase_extra_name', name);
    wx.navigateTo({
      url: "/pages/purchaseExtra/purchaseExtra"
    });
  },
  openPurchase(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let purchase = this.data.purchaseList[index];
    // console.log(purchase)

    wx.setStorageSync('purchasesStr', JSON.stringify([purchase]));
    wx.navigateTo({
      url: `/pages/purchaseDetail/purchaseDetail?id=${purchase.id}&itemId=${purchase.itemId}&index=1`
    });
  },
  quote(event) {
    let index = event.currentTarget.dataset.index;
    let purchase = this.data.purchaseList[index];
    wx.setStorageSync('purchaseListStr', JSON.stringify([purchase]));
    wx.navigateTo({
      url: `/pages/quote/quote`
    })
  },
  onChange(e) {
    this.setData({
      searchValue: e.detail,
    });
  },
  onSearch() {
    this.getSupplyList();
    this.getIndexData();
  },
  onLoad: function (options) {},
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // user.ApproveRequestSubscribeMessage(function () {
    //   wx.switchTab({
    //     url: "/pages/supply/supply"
    //   });
    // });
    //保存登录状态 TODO
    let userInfo = wx.getStorageSync('userInfo');
    let token = wx.getStorageSync('token')
    if (userInfo && token) {
      app.globalData.hasLogin = true;
    }
    // 页面显示
    if (app.globalData.hasLogin) {
      this.setData({
        hasLogin: true
      });
      // this.getIndexData();
      // wx.showTabBar();
      this.checkShopInfo();
    } else {
      this.getPosterData();
      wx.hideTabBar();
    }
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  onShareAppMessage: function () {
    wx.showShareMenu({
      withShareTicket: true,
      menu: ['shareAppMessage', 'shareTimeline']
    });
    return {
      title: '鹿升升采购'
    };
  },
  onShareTimeline() {
    return {
      title: '鹿升升采购',
      imageUrl: '/static/images/logo.png'
    };
  },
  playVideo(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let purchase = this.data.purchaseList[index];
    this.setData({
      video_data: purchase.herbVideo
    });
    this.play();
  },
  play(e) {
    //执行全屏方法  
    this.videoContext = wx.createVideoContext('myvideo', this);
    this.videoContext.requestFullScreen();
    // this.videoContext.play();
    this.setData({
      fullScreen: true
    })
  },
  /**关闭视屏 */
  closeVideo() {
    //执行退出全屏方法
    this.videoContext.exitFullScreen();
  },
  /**视屏进入、退出全屏 */
  fullScreen(e) {
    var isFull = e.detail.fullScreen;
    //视屏全屏时显示加载video，非全屏时，不显示加载video
    this.setData({
      fullScreen: isFull
    })
  },
  addWantBuy(){
    wx.navigateTo({
      url: "/pages/addWantBuy/addWantBuy"
    });
  },
})